
require 'optparse'

require 'rubygems'
require 'inifile'

require 'raklur/account_factory'
require 'raklur/rdebug'

module Raklur

	class ConfigError < SyntaxError ; end

	class Config
		attr_accessor :accounts, :verbose, :debug

		#
		# FIXME: use xdg default 
		#
		def initialize argv
			@debug = false
			@accounts = []
			@config_path = "%s/.raklur/config" % ENV['HOME']
			@verbose = false

			parse_cmd_line argv
			parse_file
			validate
		end


		#
		# Parse command line
		#
		def parse_cmd_line argv
			OptionParser.new do |opts|
				opts.banner = "Usage: #{$0} [options]"
				opts.separator ""
				opts.separator "Specific options:"

				opts.on("-c", "--config FILE", "Use configuration from FILE instead of default." ) do |c|
					@config_path = c
				end

				opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
					@debug = v
					@verbose = v
				end

				opts.on("-h", "--help", "Show this help" ) do |h|
					puts opts.to_s
					exit 0
				end

				opts.parse!
			end
		end

		#
		# Parse configuration file
		#
		def parse_file
			if not File.exist? @config_path
				raise ConfigError, "Configuration file #{@config_path} does not exist."
			end

			cur_name = nil
			cur_data = {}

			f_line = 0
			rdebug "loading #{@config_path}"
			ini = IniFile.load( @config_path )
			ini.each_section do |section|
				acct = AccountFactory.create section, ini[section]
				raise ConfigError.new "Unable to create account for #{section}" if acct.nil?
				@accounts << acct 
			end
		end

		#
		# 
		#
		def validate

		end
	end
end

